/** \file lp_graph.c
 * \brief Implementation of the graph genarator for the logicparser.
 * \brief It uses the dot graph language, from GraphViz.
 * \author Marcelo Lira dos Santos
 * \date 2006-2007
 *
 * This is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License, see the file LICENSE.
 */
#include "lp_graph.h"

/** \brief Returns a 'listification' of a parsed binary tree.
 * \param node Parsed node to be inserted in the list.
 * \param list Previous list in which insert new node.
 * \return A list with the new item added.
 */
GSList *
lp_tree_to_list (LpNode *node, GSList *list)
{

	if (node != NULL) {	
		list = g_slist_append(list, node);
		
		list = lp_tree_to_list (node->left, list);
		list = lp_tree_to_list (node->right, list);
	}

	return list;
}

/** \brief Generate GraphViz graph of the parsed tree.
 * \param root Root node for the parsed tree.
 * \return A string containing the graph in DOT language
 * \return or "" if there's a problem.
 */
gchar *
lp_graph_generate (LpNode *root)
{
	gchar *nodestring;
	LpNode *node;
	GSList *list = NULL;
	GSList *list_iterator;
	gchar *label;
	gchar *node_text;
	gchar *left;
	gchar *right;
	gint i;
	
	if (root == NULL)
		return "";
	
	list = lp_tree_to_list (root, list);
	list_iterator = list;
	for (i = 0; list_iterator != NULL; i++) {
		GPOINTER_TO_LPNODE(list_iterator->data)->node_id = i;
		
		list_iterator = list_iterator->next;
	}

	nodestring = "";
	while (list != NULL) {
		node = GPOINTER_TO_LPNODE(list->data);
		//[shape=box,style=filled,color=".7 .3 1.0"]
		node_text = g_strdup_printf("%s_%d",
				lp_get_node_text(node->lpToken), node->node_id);
		
		if (IS_TERMINAL(node->lpToken->nodeType))
			label = g_strdup_printf(
				"\t%s [label=%s,shape=box,style=filled,fontname=Helvetica," \
				"color=\"#88C4F1\"];\n",
				node_text, lp_get_node_text(node->lpToken));
		else
			label = g_strdup_printf(
				"\t%s [label=%s,style=filled,fontname=Helvetica," \
				"color=\"#A5F188\"];\n",
				node_text, lp_get_node_text(node->lpToken));

		if (node->left != NULL) {
			left = g_strdup_printf("\t%s -> %s_%d;\n", node_text, 
					lp_get_node_text(node->left->lpToken), node->left->node_id);
		} else
			left = "";

		if (node->right != NULL) {
			right = g_strdup_printf("\t%s -> %s_%d;\n", node_text, 
					lp_get_node_text(node->right->lpToken), node->right->node_id);
		} else
			right = "";

		nodestring = g_strconcat(nodestring, label, left, right, NULL);

		list = list->next;
	}

	return g_strdup_printf("digraph ParsedTree\n{\n%s}\n", nodestring);
}
